package com.ruoyi.web.service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Program: RuoYi-Vue-chy->SynchronizedCounterExample
 * @Description: 使用 synchronized 同步共享资源
 * @Author: hongyu.chen
 * @Date: 2025-03-06 11:59
 * @Version： 1.0
 **/
public class SynchronizedCounterExample {
    // 共享资源
    private static int counter = 0;

    // 同步方法，确保线程安全
    public synchronized static void incrementCounter() {
        counter++;
    }

    public static void main(String[] args) {
        //获取 CPU 核心数
        int cpuCoreCount = Runtime.getRuntime().availableProcessors();
        //核心线程数
        int corePoolSize = cpuCoreCount * 2;
        //最大线程数
        int maximumPoolSize = corePoolSize * 8;
        long keepAliveTime = 60L;
        TimeUnit unit = TimeUnit.MILLISECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(1000);

        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                new ThreadPoolExecutor.CallerRunsPolicy() // 使用CallerRunsPolicy策略
        );
        List<Integer> taskIds = new ArrayList<>();

        // 提交一千个任务
        for (int i = 0; i < 1000; i++) {
            final int taskId = i;
            executor.submit(() -> {
                // 模拟 CPU 密集型任务
                for (int j = 0; j < 100000; j++) {
                    // 模拟一些计算
                    Math.sqrt(j);
                }
                // 对共享资源进行同步递增
                incrementCounter();
                System.out.println("Task " + taskId + " completed. Counter: " + counter);
                taskIds.add(taskId);
            });
        }
        System.out.println("taskIds: " + taskIds.size());

        executor.shutdown();
        try {
            // 等待所有任务完成
            if (!executor.awaitTermination(1, TimeUnit.HOURS)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
        }

        System.out.println("Final Counter Value: " + counter);
        System.out.println("taskIds2: " + taskIds.size());
    }
}
